<template>
  <div class="app-container" v-loading="loading">
    <!--患者数据-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px"
      class="formBox1 formBox searchForm">
      <el-form-item label="医院" prop="hospital" clearable>
        <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="160px" :isUserAll="true"
          ref="department">
        </department>
      </el-form-item>
      <el-form-item label="专病名称" prop="diseaseClassifyName">
        <el-select v-model="queryParams.diseaseClassifyName" filterable placeholder="请选择专病名称" clearable
          style="width: 160px">
          <el-option v-for="dict in classifyList" :key="dict.diseaseClassifyId" :label="dict.diseaseClassifyName"
            :value="dict.diseaseClassifyName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分型" prop="diseaseType">
        <el-input v-model="queryParams.diseaseType" placeholder="请输入分型" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分期" prop="diseaseSerialization">
        <el-input v-model="queryParams.diseaseSerialization" placeholder="请输入分期" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="光照类型" prop="faceLight">
        <el-select v-model="queryParams.faceLight" placeholder="采集设备" clearable filterable style="width: 160px">
          <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采集设备" prop="type">
        <el-select v-model="queryParams.type" filterable placeholder="请选择采集设备" clearable style="width: 160px">
          <el-option v-for="dict in dict.type.photo_upload_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="照片部位" prop="facePart">
        <el-select v-model="queryParams.facePart" filterable placeholder="请选择照片部位" clearable style="width: 160px">
          <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="顾客ID" prop="patientId">
        <el-input v-model="queryParams.patientId" placeholder="顾客ID" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="顾客编号" prop="visitNum">
        <el-input v-model="queryParams.visitNum" placeholder="请输入顾客编号" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入姓名" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采集状态" prop="status">
        <el-select v-model="queryParams.status" filterable placeholder="请选择状态" clearable style="width: 160px">
          <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采集时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          :picker-options="pickerOptions" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          @change="handleQuery"></el-date-picker>
      </el-form-item>

      <el-form-item label="评分">
        <el-select v-model="queryParams.introducedClassifyId" placeholder="请选择" clearable
          style="width: 160px; margin-right: 10px">
          <el-option v-for="item in introducedClassifyList" :key="item.introducedClassifyId"
            :label="item.introducedClassifyName" :value="item.introducedClassifyId"></el-option>
        </el-select>
        <el-input-number v-model="queryParams.startScore" controls-position="right" :min="0"
          :disabled="!queryParams.introducedClassifyId ? true : false" style="width: 103px" />
        ——
        <el-input-number v-model="queryParams.endScore" controls-position="right" :min="0"
          :disabled="!queryParams.introducedClassifyId ? true : false" style="width: 103px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="formBox searchForm" style="margin-bottom:0px!important;" ref="statisticalTable">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <!-- <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="multiple"
            @click="handleAdd"
            >加入标注库</el-button
          > -->
          <el-button type="primary" plain icon="el-icon-picture" size="mini">{{ photoTotal }} 张照片</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getPhotoList"></right-toolbar>
      </el-row>
      <el-table border style="width: 100%" :data="photoList" @selection-change="handleSelectionChange"
        :height="statisticalTableH" ref="table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ getIndex(scope.$index) }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="顾客ID" align="center" prop="patientId" width="100" />
        <el-table-column sortable label="顾客编号" align="center" prop="visitNum" width="160" />
        <el-table-column sortable label="照片" align="center" prop="photoNum" width="100">
          <template slot-scope="scope">

            <el-tooltip placement="right" effect="light">
              <div slot="content" class="tooltipSlotBox">
                <div class="img-txt" v-for="(item, Mindex) in scope.row.sysPatientPhotos" :key="item.photoId">
                  <div class="user-info-head" @click="watchBigPic(scope.row, Mindex)">
                    <!-- <el-image class="img-style" fit="contain" :src="item.thumbnail"
                      @click="watchBigPic(scope.row, Mindex)"></el-image> -->
                    <lazyImg class="img-style" fit="contain" :src="item.thumbnail">
                      <!-- 图片加载之前默认在图片元素上方展示的样式--自由发挥 -->
                      <div class="slotlazyImg-txt">图片加载中...</div>
                      <template #err>
                        <!-- 图片加载失败后在上面展示的样式--- 自由发挥 -->
                        <div class="slotlazyImg-txt">图片加载失败</div>
                      </template>
                    </lazyImg>
                  </div>
                </div>
              </div>
              <div>
                <el-tag type="1" size="mini">{{ scope.row.photoNum }}</el-tag>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column sortable label="顾客姓名" align="center" prop="patientName" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column sortable label="AI masi" align="center" prop="score" width="100" />

        <el-table-column sortable label="医生诊断" align="center" prop="doctorDiagnosisValue" :show-overflow-tooltip="true"
          width="180">
          <template slot-scope="scope">
            <span v-html="scope.row.doctorDiagnosisValue"></span>
          </template>
        </el-table-column>

        <el-table-column sortable label="拍照设备" align="center" prop="type" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.photo_upload_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column sortable label="采集时刻" align="center" prop="status" width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column sortable label="采集日期" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="采集人" align="center" prop="nickName" />
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getPhotoList" />
    </div>
    <el-dialog title="照片标注" :visible.sync="picMarkDialogVisible" width="100%" center :close-on-click-modal="false"
      :append-to-body="true" v-dialogDrag class="nopaddingBody fullDialog">
      <PhotoMark :currentUrl="currentUrl" :imgList="imgList" :myImgIndex="myImgIndex"
        @closedEvent="picMarkDialogVisible = false" v-if="picMarkDialogVisible">
      </PhotoMark>
    </el-dialog>
  </div>
</template>

<script>
import { listClassify } from "@/api/system/classify";
import {
  photoAnnotate,
  photoManagement,
} from "@/api/photoWorkstation/photoList";
import department from "@/views/components/department/index.vue";
import PhotoMark from "@/views/components/photoMark/photoMark.vue";

export default {
  name: "photoManagement",
  components: { department, PhotoMark },
  dicts: [
    "sys_normal_disable",
    "sys_manage_diseases",
    "sys_diagnosis_status",
    "sys_user_category",
    "sys_user_sex",
    "photo_upload_type",
    "sys_face_part",
    "photo_lighting_type",
  ],
  data() {
    return {
      statisticalTableH: undefined,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      listTotal: 0,
      // 照片表格数据
      photoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      classifyList: [], //专病管理
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              const end = date;
              const start = date;
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "前天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
              const end = date;
              const start = date;
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近1年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        aitype: undefined,
        createBy: undefined,
        createTime: undefined,
        deptId: undefined,
        diseaseClassifyName: undefined, //专病名称
        diseaseSerialization: undefined, //专病分期
        diseaseType: undefined, //专病分型
        endScore: undefined,
        facePart: undefined,
        faceLight: undefined,
        patientId: undefined,
        patientName: undefined,
        remark: undefined,
        searchValue: undefined,
        startScore: undefined,
        status: undefined,
        type: undefined,
        visitNum: undefined,
        introducedClassifyId: "0",
        hospitalId: undefined,
      },
      introducedClassifyList: [
        {
          introducedClassifyId: "0",
          introducedClassifyName: "AI mMASI",
        },
      ],
      picMarkDialogVisible: false,
      currentUrl: "",
      imgList: [],
      myImgIndex: "", //picData 第几组的index下 第几个照片的index
      photoTotal: 0,

    };
  },
  watch: {
    showSearch() {
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)

    }
  },
  mounted() {
    this.changeHeight()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    changeHeight() {
      if (this.$refs.statisticalTable) {
        const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
        let h = statisticalTableObj.top + 100
        this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
      } else {
        this.statisticalTableH = '500px'
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.pindex);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        aitype: undefined,
        createBy: undefined,
        createTime: undefined,
        deptId: undefined,
        diseaseClassifyName: undefined, //专病名称
        diseaseSerialization: undefined, //专病分期
        diseaseType: undefined, //专病分型
        endScore: undefined,
        facePart: undefined,
        faceLight: undefined,
        patientId: undefined,
        patientName: undefined,
        remark: undefined,
        searchValue: undefined,
        startScore: undefined,
        status: undefined,
        type: undefined,
        visitNum: undefined,
        introducedClassifyId: "0",
        hospitalId: undefined,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPhotoList();
    },
    handleAdd() {
      const index = this.ids;
      console.log("handleAdd---", { index });
      this.$modal
        .confirm("是否将勾选的照片加入标注库?")
        .then(function () {
          return photoAnnotate({ index });
        })
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
          }
        })
        .catch(() => { });
    },
    watchBigPic(row, Mindex) {
      console.log("---------+++++++", row, Mindex);
      this.myImgIndex = Mindex;
      this.currentUrl = row.sysPatientPhotos[Mindex].photoAddress;
      row.sysPatientPhotos.forEach((item) => {
        item.patientName = row.patientName;
        item.age = row.age;
        item.photoType = row.photoType;
        item.photoIndex = row.pindex;
        item.doctorDiagnosis = row.doctorDiagnosis.replace(
          / *\([^)]*\) */g,
          ""
        );
        if (item.score && JSON.parse(item.score).left) {
          item.scoreAi =
            0.3 *
            JSON.parse(item.score).left.area *
            JSON.parse(item.score).left.color;
        }
        if (item.score && JSON.parse(item.score).brow) {
          item.scoreAi =
            0.3 *
            JSON.parse(item.score).brow.area *
            JSON.parse(item.score).brow.color +
            0.1 *
            JSON.parse(item.score).chin.area *
            JSON.parse(item.score).chin.color;
        }
        if (item.score && JSON.parse(item.score).right) {
          item.scoreAi =
            0.3 *
            JSON.parse(item.score).right.area *
            JSON.parse(item.score).right.color;
        }
      });
      this.imgList = row.sysPatientPhotos;
      this.picMarkDialogVisible = true;
    },
    refreshData(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.hospitalId = data.hospitalId;
      this.queryParams.deptId = data.deptId;
    },
    // 获取专病列表
    getClassifyList() {
      listClassify({
        pageNum: 1,
        pageSize: 9999,
        status: "0",
      }).then((response) => {
        this.classifyList = response.rows;
      });
    },
    getPhotoList() {
      this.loading = true;
      console.log("this.queryParams", this.queryParams);

      photoManagement(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          if (response.code == 200) {
            this.photoList = response.rows;
            this.photoList.forEach((item) => {
              if (item.doctorDiagnosis.includes(";")) {
                let MobjectDoctor = "";
                item.doctorDiagnosis.split(";").forEach((it) => {
                  MobjectDoctor += it + "<br>";
                });
                item.doctorDiagnosisValue = MobjectDoctor;
              } else {
                item.doctorDiagnosisValue = item.doctorDiagnosis;
              }
              if (item.score) {
                item.score = Number(item.score).toFixed(1);
              } else {
                item.score = "";
              }
            });
            this.total = response.total;
            this.photoTotal = response.data;
          }
          this.loading = false;
        }
      );
    },
  },
  created() {
    this.getClassifyList();
    this.handleQuery();
  },
};
</script>

<style scoped rel="stylesheet/scss" lang="scss">
.tooltipSlotBox::-webkit-scrollbar {
  display: none;

}

.tooltipSlotBox {
  max-width: 460px;
  max-height: 200px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;

  .img-txt {
    //display: flex;
    //flex-direction: column;
    //text-align: center;
    //margin: 14px;
    margin: 6px;

    .user-info-head {
      width: 80px;
      height: 104px;

      //border: 1px solid #000;
      .img-style {
        width: 100%;
        height: 100%;

        ::v-deep .el-image__error {
          opacity: 0;
        }
      }
    }
  }
}
</style>
